//检测是否登陆
getUserName();

$('header .login a:lt(1)').click(function () {
    $('.log').show();
})
//登录
function login() {
    if (accountVerify() && passVerify()) {
        $.post(
            "http://ns.iyaokao.com/show/login/do_login.action",
            $("#pop-login-form").serialize(),
            function (data) {
                var data = $.parseJSON(data);
                var res = data.res;
                console.log(res)
                if (res != "suc") {
                    console.log(false);
                    if (res.indexOf("cookie") >= 0) {
                        location.href = "http://ns.iyaokao.com/show/login/show_error_page.action?errorMsg=" + res;
                    } else {
                        //显示验证码
                        var userLoginNum = data["userLoginNum"];
                        if (userLoginNum >= 3) {
                            $(".yanzhen").show();
                            changeRandom();
                        }
                        layer.msg(res, { time: 2000 });
                    }
                } else {
                    console.log(true);
                    layer.msg("登录成功", { time: 2000 });
                    getUserName();
                    $('.log').hide();
                }
            }
        );
    }
}

//点击提交事件
$("#pop-loginSubmit").click(function () {
    login();
});

//手机验证
function accountVerify() {
    var uname = $("input[name='uname']")
        .val()
        .trim();
    if (uname.length == 0) {
        layer.msg("请输入账号", { time: 2000 });
        return false;
    }
    return true;
}

//密码验证
function passVerify() {
    var upwd = $("input[name='upwd']")
        .val()
        .trim();
    if (upwd == "") {
        layer.msg("请输入密码", { time: 2000 });
        return false;
    }
    return true;
}

//验证码
function changeRandom() {
    $(".yanzhen img").attr("src", "http://ns.iyaokao.com/show/login/random.action?d=" + Math.random());
}
$(".yanzhen i").click(function () {
    changeRandom();
});

//关闭弹窗
$(".icon-guanbi").click(function () {
    $(".log").css("display", "none");
});
//切换到登录
$(".register .remember a").click(function () {
    $(".pop-login").css("display", "block");
    $(".register").css("display", "none");
});
$(".register .info a").click(function () {
    $(".pop-login").css("display", "block");
    $(".register").css("display", "none");
});
//切换到注册
$(".pop-login .info a").click(function () {
    $(".pop-login").css("display", "none");
    $(".register").css("display", "block");
});

//注册
//回车键焦点事件
/* var index = "";
var inp = "";
$(function() {
    var inputs = $("input");
    inputs.bind("keydown", function(e) {
        var key = e.which;
        if (key == 13) {
            e.preventDefault();
            index = inputs.index(this) + 1;

            //获得焦点
            inp = $("input:eq(" + index + ")");
            inp.focus();
            if (inp.attr("type") == "button") {
                validate();
            }
        }
    });
}); */

$("#register .submit a").click(validate);
function validate() {
    // $("#validateBtn").attr("disabled", "disabled");

    if (
        telphoneValidate() &&
        validateCode() &&
        upwdValidate() &&
        reUpwdValidate()
    ) {
        $.ajaxSetup({ async: false });
        $.post(
            "http://ns.iyaokao.com/show/login/register.action",
            $("#register").serialize(),
            function (data) {
                var dataJson = $.parseJSON(data);
                console.log(dataJson);
                var res = dataJson["res"];
                if (res == "suc") {
                    layer.msg("注册成功，登录中..", { time: 2000 });
                    getUserName();
                    $('.log').hide();
                } else {

                    //错误信息显示
                    layer.msg(res, { time: 2000 });
                }
            }
        );
    }
}

//密码格式验证
function upwdValidate() {
    var upwdRegex = /^\w{6,16}$/;
    var upwd = $("#register .upwd").val();
    if (upwd.length < 6 || upwd.length > 16) {
        layer.msg("请输入6-16位密码", { time: 2000 });
        return false;
    }
    if (!upwdRegex.test(upwd)) {
        layer.msg("密码只能为英文数字下划线", { time: 2000 });
        return false;
    }
    return true;
}

//重复密码验证
function reUpwdValidate() {
    var upwdRegex = /^\w{6,16}$/;
    var upwd = $("#register .upwd").val();
    var qupwd = $("#register .qupwd").val();
    if (upwd != qupwd) {
        layer.msg("两次密码不一致", { time: 2000 });
        return false;
    }
    return true;
}

//验证码验证
function validateCode() {
    var validateCodeFlag = true;
    var validateCode = $("#register .validateCode").val();

    if (validateCode.trim() == "") {
        layer.msg("请输入验证码", { time: 2000 });
        return false;
    }

    $.ajaxSetup({ async: false });
    $.post(
        "http://ns.iyaokao.com/show/login/register_code_validate.action",
        { validateCode: validateCode },
        function (data) {
            if (data != "suc") {
                layer.msg("验证码错误", { time: 2000 });
                validateCodeFlag = false;
            }
        }
    );
    return validateCodeFlag;
}

//手机号验证
function telphoneValidate() {
    var telphoneFlag = true;
    var telphone = $("#register .telphone").val().trim();
    var telphoneRegex = /(^(\\d{3,4}-)?\\d{7,8})$|(1[0-9]{10})/;
    if (!telphoneRegex.test(telphone)) {
        layer.msg("手机号错误", { time: 2000 });
        return false;
    }
    $.ajaxSetup({ async: false });
    $.post(
        "http://ns.iyaokao.com/show/login/register_telphone_validate.action",
        { telphone: telphone },
        function (data) {
            if (data != "suc" && data != "手机号不存在") {
                layer.msg(data, { time: 2000 });
                telphoneFlag = false;
            }
        }
    );
    return telphoneFlag;
}

//发送短信验证码
var messageBtn = $("#register .yanzhen-phone a");
messageBtn.click(sendMessage);
function sendMessage() {
    //发送短信限制
    var telphoneFlag = telphoneValidate();
    if (!telphoneFlag) return; //手机号不通过验证，不可发送短信

    messageBtn.addClass("active");

    var telphone = $("#register .telphone").val();
    $.ajaxSetup({ async: false });
    $.get(
        "http://ns.iyaokao.com/show/login/send_code_by_telphone.action",
        { telphone: telphone, sendType: 1 },
        function (data) {
            var resData = $.parseJSON(data);
            if (resData["res"] == "suc") {
                layer.msg("发送成功，请注意查收！！", { time: 2000 });

                timing(); //倒计时
            } else {
                messageBtn.removeClass("active");
                layer.msg(resData.res, { time: 2000 });
            }
        }
    );
}

//发送短信时间间隔
function timing() {
    messageBtn.off("click"); //取消点击事件

    var second = 60;
    var btn = $("#register .yanzhen-phone a");

    var timer = setInterval(function () {
        second--;
        btn.html(`${second}s`);
        if (second == 0) {
            clearInterval(timer);
            messageBtn.removeClass("active");
            btn.html("发送验证码");
            second = 60;
            messageBtn.click(sendMessage);
        }
    }, 1000);
}

//获取用户的账号名
function getUserName() {
    $.post("http://ns.iyaokao.com/show/login/val_user_login.action", function (data) {
        var data = $.parseJSON(data);
        if (data.uname != "") {
            $('.header-2 .login-before').hide();
            $('.header-2 .login-after').show();
            $('.header-2 .login-after a:eq(0)').html(data.uname);
        }
    });
}

//注销
function logout() {
    $.post('http://ns.iyaokao.com/show/login/logout.action', function () {
        layer.msg('注销成功', { time: 2000 });
    });
    $('.header-2 .login-before').show();
    $('.header-2 .login-after').hide();
    $('.header-2 .login-after a:eq(0)').html('');
}

$('.login-after').click(logout);
